package com.boxin.ims.modules.wechat.busi;

import java.io.File;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.boxin.ims.modules.sys.utils.ImageUtils;
import com.boxin.ims.modules.wechat.entity.RecommendConfig;
import com.boxin.ims.modules.wechat.entity.WeChat;
import com.boxin.ims.modules.wechat.entity.WechatMember;
import com.boxin.ims.modules.wechat.entity.WechatScene;
import com.boxin.ims.modules.wechat.service.RecommendConfigService;
import com.boxin.ims.modules.wechat.service.WeChatService;
import com.boxin.ims.modules.wechat.service.WechatSceneService;
import com.boxin.ims.modules.wechat.utils.TokenUtils;
import com.boxin.ims.modules.wechat.utils.WechatInterfaceUtils;
import com.boxin.ims.modules.wechat.utils.WechatUtils;

import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.common.utils.DateUtils;
//import com.thinkgem.jeesite.common.utils.JedisUtils;
import com.thinkgem.jeesite.modules.sys.entity.User;

/**
 * 三级推广：生成推广海报
 * @author Administrator
 *
 */
@Service
@Scope("prototype")
public class ExpandQrcodeProcessor extends BusinessProcessor{
	@Autowired
	private WeChatService weChatService;
	
	@Autowired
	private WechatSceneService wechatSceneService;
	
	@Autowired
	private RecommendConfigService recommendConfigService;
	

	/*public RecommendConfig getRecommendConfig(String uid){
		String key = "recommend_config_"+uid;
		Object object = CacheUtils.get(key);
		if(object!=null){
			return (RecommendConfig) object;
		}else{
			object =	JedisUtils.getObject(key);
			if(object!=null){
				return (RecommendConfig) object;
			}else{
				RecommendConfig config = recommendConfigService.getByUserId(Long.parseLong(uid));
				JedisUtils.setObject(key, config, 0);
				CacheUtils.put(key, config);
				return config;
			}
		}
	}*/
	
	
	public RecommendConfig getRecommendConfig(String uid){
		String key = "recommend_config_"+uid;
		Object object = CacheUtils.get(key);
		if(object!=null){
			return (RecommendConfig) object;
		}else{
			object =	CacheUtils.get(key);
			if(object!=null){
				return (RecommendConfig) object;
			}else{
				RecommendConfig config = recommendConfigService.getByUserId(Long.parseLong(uid));
				CacheUtils.put(key, config);
				return config;
			}
		}
	}
	
	@Override
	public ProcessMessage process() {
		
		RecommendConfig recommendConfig = getRecommendConfig(user.getId().toString());
		if(recommendConfig==null) return null;
		Date date = new Date();
		if(RecommendConfig.NO.equals(recommendConfig.getIsOpen()) || recommendConfig.getStartTime().getTime()>date.getTime()) {
			writeToUser("活动未开始");
			return null;
		}
		if(date.getTime()>recommendConfig.getEndTime().getTime()){
			writeToUser("活动已结束");
			return null;
		}
		
		try {
			WechatMember member = wechatMemberService.getByWechatMemberId(user, openId);
			if(StringUtils.isBlank(member.getRecommendPic()) || member.getRecommendEndTime()==null || member.getRecommendEndTime().getTime()-new Date().getTime()<0){
				//生成二维码
				WechatScene wechatScene = sceneCodeByMemberId(member);
				
				//获取背景图片
				//String picFilePath = WechatUtils.getRecommendSavePath(request).replaceAll("\\\\", "\\\\\\\\")+File.separator+recommendConfig.getRecommendPic();
				String picFilePath = WechatUtils.getRecommendSavePath(request)+File.separator+recommendConfig.getRecommendPic();
				//生成推广图片
				String tuiGuang = ImageUtils.posterImage(picFilePath, member, wechatScene.getTicket(), recommendConfig, request);
				
				member.setRecommendSceneId(wechatScene.getSceneId());
				member.setRecommendPic(tuiGuang);
				member.setRecommendEndTime(DateUtils.getDelayDate(28));
				member.setRecommendPicBg(recommendConfig.getRecommendPic());
				wechatMemberService.save(member);
			}else if(StringUtils.isNotBlank(member.getRecommendPicBg()) && !recommendConfig.getRecommendPic().equals(member.getRecommendPicBg())){
				//获取二维码
				WechatScene wechatScene = wechatSceneService.wechatSceneBySceneId(user.getId(), member.getId()+"");
				//获取背景图片
				//String picFilePath = WechatUtils.getRecommendSavePath(request).replaceAll("\\\\", "\\\\\\\\")+File.separator+recommendConfig.getRecommendPic();
				String picFilePath = WechatUtils.getRecommendSavePath(request)+File.separator+recommendConfig.getRecommendPic();
				//生成推广图片
				String tuiGuang = ImageUtils.posterImage(picFilePath, member, wechatScene.getTicket(), recommendConfig, request);
				
				member.setRecommendPic(tuiGuang);
				member.setRecommendPicBg(recommendConfig.getRecommendPic());
				wechatMemberService.save(member);
			}
			
			String content = recommendConfig.getMessage().replaceAll("endTime",DateUtils.getNumberByDate1(member.getRecommendEndTime()));
			WechatInterfaceUtils.sendTextMessageToMember1(user.getId(), member, content);
			
			String mediaId = getMediaId(user.getId(), member.getRecommendPic(), member);
			imageToUser(mediaId);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}

	@Override
	public boolean isNeedBeMember() {
		// TODO Auto-generated method stub
		return false;
	}
	
	/**
	 * 生成临时推广码
	 *@author xiaoqian
	 * @param wechatMember
	 * @return
	 * 2015-4-7下午6:02:06
	 */
	public WechatScene sceneCodeByMemberId(WechatMember wechatMember){
		WechatScene wechatScene = wechatSceneService.wechatSceneBySceneId(wechatMember.getUser().getId(), wechatMember.getId()+"");
		if(wechatScene==null){
			wechatScene = new WechatScene();
		}
		wechatScene.setUser(wechatMember.getUser());
		wechatScene.setType(WechatScene.SCENE_TYPE_RECOMMEND_TEMP);		//三级推广二维码
		
		if(wechatScene.getSceneId()==null){
			Long sceneId=wechatMember.getId();
			wechatScene.setSceneId(sceneId);
		}
		
		String ticket = getTicket(wechatScene);
		wechatScene.setTicket(ticket);
		wechatScene.setProcessorId("expandProcessor");
		wechatScene.setScene(wechatMember.getNickname()+"("+wechatMember.getId()+")");
		wechatSceneService.save(wechatScene);
		
		return wechatScene;
	}
	
	
	/**
	 * 获取临时二维码
	 * @param wechatScene
	 * @return
	 */
	public String getTicket(WechatScene wechatScene){
		String qrcodeparams="";
		JSONObject object = null;
		wechatScene.setQrcodeType("QR_SCENE");
		try {
			WeChat weChat= weChatService.getWeChatByUserId(user.getId());
			String accessToken=TokenUtils.getAPIToken(weChat);
			qrcodeparams=WechatInterfaceUtils.createTemporaryQrCodeParams("2590000", wechatScene.getSceneId().toString());
			object=WechatInterfaceUtils.createQrCode(qrcodeparams, accessToken);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		System.out.println("生成新ticket："+object.getString("ticket"));
//		return "gQF68DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyNW84b01KVkViVy0xMDAwMHcwM0cAAgRLQFdYAwQAAAAA";
		return object.getString("ticket");
	}
	
	
	/**
	 * 上传图片，获取图片ID
	 * @param uid
	 * @param path
	 * @param member
	 * @return
	 */
	public String getMediaId(long uid,String path,WechatMember member){
		String mediaId = "";
		WeChat weChat =  weChatService.getWeChatByUserId(uid);
		String token = TokenUtils.getAPIToken(weChat);
		
//		String token=TokenUtils.getAPITokenByuser(uid);
		
		String filepath = path;
		File file = new File(filepath);
		try {
			mediaId = WechatInterfaceUtils.uploadMedia("image", file, token);
		} catch (Exception e) {
			logger.error("上传图片", e);
		}
		return mediaId;
	}
}
